<template>
  <div class='video-container both-100'>
    <div class="play-btn">
      <img src="@/assets/images/play.png" @click="clickPlayer()" v-if="!isPlayer" />
    </div>
    <video :id="elementId" class="video" crossOrigin="anonymous" controls autoplay muted width="100%" height="100%"></video>
  </div>
</template>

<script>
import flvjs from 'flv.js'
import { previewDeviceCamera } from './camera'
export default {
  name: 'videoPreview',
  props: {
    elementId: {
      type: String,
      default: 'videoElement',
      require: true
    },
    // 是否为直播
    live: {
      type: Boolean,
      default: true
    },
    code: {
      type: String,
      default: '',
      require: true
    },
  },
  data () {
    return {
      videoUrl: '',
      // 初始化实例
      player: undefined,
      // 是否为播放状态
      isPlayer: false
    };
  },
  watch: {
    elementId: {
      handler (newVal, oldVal) {
        this.destoryVideo()
      }
    }
  },
  created () {
    // this.initVideoPlayer()
    if (this.live) {
      // previewDeviceCamera
    }
  },
  mounted () {

  },
  computed: {
    isLiveModel () {
      return this.live

    },
  },
  methods: {
    // 点击播放按钮
    clickPlayer () {
      this.$nextTick(() => {
        this.initVideoPlayer()
      })
      this.isPlayer = true
    },
    // 获取code进行查询（
    async getVideoUrl () {
      const params = {
        cameraIndexCode: this.code,
        clientType: 0
      }
      const res = await previewDeviceCamera(params)
      return res.data
    },
    // 加载直播视频流
    async initVideoPlayer () {
      if (flvjs.isSupported()) {
        console.log(this.elementId)
        var videoElement = document.getElementById(this.elementId);
        var url = await this.getVideoUrl()
        if (!url) {
          this.$message.error("没有视频资源")
          this.isPlayer = false
          return
        }
        this.videoUrl = '/' + url
        this.player = flvjs.createPlayer({
          type: 'flv',
          isLive: true,
          hasAudio: false,
          url: this.videoUrl,	// 自己的flv视频流
          enableWorker: false, //启用 Web Worker 进程来加速视频的解码和处理过程
          stashInitialSize: 32 * 1024, // 初始缓存大小。单位：字节。建议针对直播：调整为1024kb
          stashInitialTime: 0.2, // 缓存初始时间。单位：秒。建议针对直播：调整为200毫秒
          seekType: "range", // 建议将其设置为“range”模式，以便更快地加载视频数据，提高视频的实时性。
          lazyLoad: false, //关闭懒加载模式，从而提高视频的实时性。建议针对直播：调整为false
          lazyLoadMaxDuration: 0.2, // 懒加载的最大时长。单位：秒。建议针对直播：调整为200毫秒
          deferLoadAfterSourceOpen: false,
        }, {
          cors: true, // 是否跨域
          // enableWorker: true, // 是否多线程工作
          enableStashBuffer: false, // 是否启用缓存
          // stashInitialSize: 128, // 缓存大小(kb)  默认384kb
          autoCleanupSourceBuffer: true, // 是否自动清理缓存
        });
        this.player.attachMediaElement(videoElement);//挂载元素
        this.player.load();//加载流
        this.player.pause();//播放流
        this.player.play();
        // 追帧
        if (this.timerId !== null) {
          clearInterval(this.timerId);
        }
        this.timerId = setInterval(() => {
          if (videoElement.buffered.length > 0) {
            const end = videoElement.buffered.end(0); // 视频结尾时间
            const current = videoElement.currentTime; //  视频当前时间
            const diff = end - current; // 相差时间
            const diffCritical = 4; // 这里设定了超过4秒以上就进行跳转
            const diffSpeedUp = 1; // 这里设置了超过1秒以上则进行视频加速播放
            const maxPlaybackRate = 4; // 自定义设置允许的最大播放速度
            let playbackRate = 1.0; // 播放速度
            if (diff > diffCritical) {
              videoElement.currentTime = end - 1.5;
              playbackRate = Math.max(1, Math.min(diffCritical, 16));
            } else if (diff > diffSpeedUp) {
              playbackRate = Math.max(1, Math.min(diff, maxPlaybackRate, 16));
            }
            videoElement.playbackRate = playbackRate;
          }
        }, 1000);
      }
      // 报错重连
      this.player.on(flvjs.Events.ERROR, (err, errdet) => {
        // 参数 err 是一级异常，errdet 是二级异常
        if (err == flvjs.ErrorTypes.MEDIA_ERROR) {
          console.log('媒体错误')
          if (errdet == flvjs.ErrorDetails.MEDIA_FORMAT_UNSUPPORTED) {
            console.log('媒体格式不支持')
          }
        }
        if (err == flvjs.ErrorTypes.NETWORK_ERROR) {
          console.log('网络错误')
          if (errdet == flvjs.ErrorDetails.NETWORK_STATUS_CODE_INVALID) {
            console.log('http状态码异常')
          }
        }
        if (err == flvjs.ErrorTypes.OTHER_ERROR) {
          console.log('其他异常：', errdet)
        }
        if (this.player) {
          this.destoryVideo()
          // this.initVideoPlayer()
        }
      })

    },
    destoryVideo () {
      if (this.player) {
        this.isPlayer = false
        this.player.pause();// 暂停播放数据流
        this.player.unload();// 取消数据流加载
        this.player.detachMediaElement();// 将播放实例从节点中取出
        this.player.destroy(); // 销毁播放实例
        this.player = null;
      }
    }
  },
  beforeDestroy () {
    console.log('销毁')
    this.destoryVideo()
  },
  components: {},
}
</script>

<style lang='less' scoped>
.video-container {
  position: relative;

  .play-btn {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    z-index: 100;
    cursor: pointer;
  }
}

.video {
  object-fit: fill;
  z-index: 99;
}

video::-webkit-media-controls-timeline {
  display: none;
}

video::-webkit-media-controls-current-time-display,
video::-webkit-media-controls-time-remaining-display {
  display: none;
}
</style>